package org.charlott2.fruitrec

import android.Manifest
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.charlott2.fruitrec.ui.theme.FruitRecognizeTheme


class MainActivity : ComponentActivity() {
    // 请求相机权限
    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            // 此处是权限请求后的回调
            // isGranted: 是否有对应权限
            if (isGranted) {
                Log.d("aa", "有相机权限")
                // 有权限是 做什么事情 写在此处
                takePictureLauncher.launch(null)
            } else {
                Log.d("aa", "没有相机权限")
            }
        }

    // 拍照结果
    private var imageForInference by mutableStateOf<Bitmap?>(null)

    // 拍照
    private val takePictureLauncher =
        registerForActivityResult(ActivityResultContracts.TakePicturePreview()) { bitmap: Bitmap? ->
            // 此处的 bitmap 代表拍摄的结果
            if (bitmap != null) {
                Log.d("aa", "图片拍摄成功")
                // 拍摄结果通常要存储下来
                imageForInference = bitmap
                // 将拍照结果进行预测
                inferenceResult = AIManager.getInstance().inference(imageForInference!!)
            } else {
                Log.d("aa", "取消拍摄图片")
            }
        }

    fun takePhoto() {
        // 请求相机权限
        requestPermissionLauncher.launch(Manifest.permission.CAMERA)
    }

    // 选择本地图片
    private val pickContent =
        registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
            if (uri != null) {
                val inputStream = contentResolver.openInputStream(uri)
                imageForInference = BitmapFactory.decodeStream(inputStream)
                // 将选择的图片进行预测
                inferenceResult = AIManager.getInstance().inference(imageForInference!!)
            }
        }

    // 选择图片
    fun pickPhoto() {
        // 请求相机权限
        pickContent.launch("image/*")
    }

    // 定义预测结果
    private var inferenceResult by mutableStateOf<Map<String, String>?>(null)

    // Activity 创建时执行的钩子
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        // 初始化AI模型
        AIManager.getInstance().init(this)

        setContent {
            FruitRecognizeTheme {
                // A surface container using the 'background' color from the theme
                // 一个表面容器应用了背景主题色
                Surface(
                    // 类似 css 样式
                    modifier = Modifier.fillMaxSize(),
                    // 背景色
                    color = MaterialTheme.colorScheme.background
                ) {
                    BaseContent(this, imageForInference, inferenceResult)
                }

            }
        }
    }
}

@Composable
fun BaseContent(
    ctx: MainActivity,
    imageForInference: Bitmap?,
    inferenceResult: Map<String, String>?
) {
    Column(
        modifier = Modifier.padding(top = 60.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        // 按钮
        Button(colors = ButtonDefaults.buttonColors(Color(0xFFFFC31A)),
            modifier = Modifier.fillMaxWidth(0.6f),
            onClick = { ctx.takePhoto() }) {
            Text(
                text = "拍照", color = Color.White
            )
        }

        Spacer(modifier = Modifier.height(16.dp))

        Button(colors = ButtonDefaults.buttonColors(Color(0xFFFFC31A)),
            modifier = Modifier.fillMaxWidth(0.6f),
            onClick = {
                ctx.pickPhoto()
            }) {
            Text(
                text = "选择图片", color = Color.White
            )
        }

        Spacer(modifier = Modifier.height(16.dp))

        if (imageForInference != null) {
            Image(
                modifier = Modifier
                    .fillMaxWidth(0.8f)
                    .padding(16.dp)
                    .aspectRatio(1f)
                    .border(BorderStroke(1.dp, Color.Gray)),
                painter = BitmapPainter(imageForInference.asImageBitmap()),
                contentDescription = "",
                contentScale = ContentScale.FillWidth,
            )
        }

        Spacer(modifier = Modifier.height(16.dp))

        if (inferenceResult != null) {
            Row {
                Text(
                    text = "AI识别的水果为：",
                    fontSize = 20.sp
                )
                Text(
                    text = "${inferenceResult["type"]}",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFFFFC31A)
                )
            }

            Spacer(modifier = Modifier.height(16.dp))

            Row {
                Text(
                    text = "参考单价为：",
                    fontSize = 20.sp
                )
                Text(
                    text = "${inferenceResult["price"]} ￥/kg",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFFFFC31A)
                )
            }
        }
    }
}
